<template>
  <div class="app-container">
    <el-form
      ref="ruleForm"
      v-loading="loading"
      :model="ruleForm"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="需求标题" prop="title" class="title">
        <el-input v-model="ruleForm.title" placeholder="请输入需求名称" />
      </el-form-item>
      <el-form-item label="需求描述" prop="description" class="description">
        <el-input
          type="textarea"
          :rows="5"
          placeholder="请输入描述"
          v-model="ruleForm.description"
        />
      </el-form-item>
      <el-form-item label="预算" prop="budget" class="budget">
        <el-input-number v-model="ruleForm.budget" :step="100" :min="0" />
      </el-form-item>

      <el-form-item label="图片" prop="dataList">
        <el-upload
          action="' '"
          list-type="picture-card"
          :limit="3"
          show-file-list
          :auto-upload="false"
          :on-change="change"
          multiple
          v-model="ruleForm.dataList"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >立即发布</el-button
        >
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { queryAccountList } from "@/api/account";
import { createItem } from "@/api/item";

export default {
  name: "AddMyItem",
  data() {
    var checkbudget = (rule, value, callback) => {
      if (value <= 0) {
        callback(new Error("必须大于0"));
      } else {
        callback();
      }
    };
    return {
      ruleForm: {
        title: "",
        description: "",
        dataList: "",
        budget: 0,
      },
      accountList: [],
      rules: {
        title: [
          { required: true, message: "请输入需求标题", trigger: "change" },
        ],
        description: [
          { required: true, message: "请输入需求描述", trigger: "change" },
        ],
        dataList: [{ required: false, message: "请上传图片", trigger: "blur" }],
        budget: [{ validator: checkbudget, trigger: "blur" }],
      },
      loading: false,
    };
  },
  computed: {
    ...mapGetters(["accountId"]),
  },
  created() {
    queryAccountList().then((response) => {
      if (response !== null) {
        // 过滤掉管理员
        this.accountList = response.filter((item) => item.userName !== "admin");
      }
    });
  },
  methods: {
    change(file, fileList) {
      //将每次图片数组变化的时候，实时的进行监听，更改数组里面的图片数据
      var arr = [];
      fileList.forEach((item) => {
        arr.push(item.raw);
      });
      this.ruleForm.dataList = arr;
      //   console.log(arr);
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        const formData = new FormData();
        var that = this;
        // 首先判断是否上传了图片，如果上传了图片，将图片存入到formData中
        console.log(this.ruleForm.dataList);
        if (this.ruleForm.dataList) {
          that.ruleForm.dataList.forEach((item, index) => {
            // console.log(item)
            formData.append(index, item);
          });
        }
        if (valid) {
          this.$confirm("是否立即创建?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "success",
          })
            .then(() => {
              this.loading = true;
              createItem({
                poster: this.accountId,
                price: this.ruleForm.budget,
                title: this.ruleForm.title,
                description: this.ruleForm.description,
              })
                .then((response) => {
                  this.loading = false;
                  if (response !== null) {
                    this.$message({
                      type: "success",
                      message: "创建成功!",
                    });
                  } else {
                    this.$message({
                      type: "error",
                      message: "创建失败!",
                    });
                  }
                })
                .catch((_) => {
                  this.loading = false;
                });
            })
            .catch(() => {
              this.loading = false;
              this.$message({
                type: "info",
                message: "已取消创建",
              });
            });
        } else {
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    selectGet(accountId) {
      this.ruleForm.poster = accountId;
    },
    // 强制更新测试文本信息框的值
    changeMessage() {
      this.$forceUpdate();
    },
  },
};
</script>

<style scoped>
</style>
